/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.client.veditor.model;

import java.util.HashMap;
import javax.jcr.PropertyType;
import javax.swing.text.Element;
import javax.swing.text.html.HTML.Tag;
import javax.swing.text.html.HTML.Attribute;
import offset.nodes.Constants;
import offset.nodes.client.model.AppletUtil;
import offset.nodes.client.model.NodeTypes;
import offset.nodes.client.model.SimpleNamespaceRegistry;
import offset.nodes.client.virtual.model.jcr.QName;
import offset.nodes.client.virtual.model.jcr.nodetype.NodeTypeDefinition;
import offset.nodes.client.virtual.model.jcr.nodetype.PropertyDefinition;
import offset.nodes.client.editor.Editor;
import offset.nodes.client.editor.model.DocumentContext;
import offset.nodes.client.editor.model.HyperlinkModel;
import offset.nodes.client.editor.model.ImageModel;
import offset.nodes.client.editor.model.Range;

/**
 *
 * @author Walter Lütgenau
 */
public class VirtualImageModel extends ImageModel {

    DataModel dataModel = null;

    public VirtualImageModel(DocumentContext context, Editor editor) {
        super(context, editor);
        this.dataModel = new DataModel(context, editor.getProperties());
    }

    /**
     * Return the parent node type. For images, the path is not used, only the last element is necessary.
     *
     * @param e The element, whose parent node type shall be determined
     * @return the parent node type.
     */
    public String getParentNodeType(Element e) {
        String parentNodeType = dataModel.getParentNodeType(e);
        int index = parentNodeType.lastIndexOf(Constants.PATH_SEPARATOR);
        if (index >= 0)
            return parentNodeType.substring(index + 1);
        return parentNodeType;
    }

    /**
     * Insert an image element for a property value referring to an icon retrieved by the IconAction.
     *
     * @param range The range within the document, that shall be substituted by the image
     * @param propertyName the name of the property
     * @param context the URL context
     * @throws java.lang.Exception
     */
    public void insertDataImage(Range range, String propertyName) throws Exception {
        if (propertyName == null || propertyName.length() == 0)
            return;

        Element e = getRealParagraph(range.getStartOffset());
        if (getRealParagraph(range.getEndOffset()) != e)
            return; // can only insert as a span into a paragraph element

        // workaround for swing bug with p-implied paragraphs
        e = getParagraphWithNoImpliedSiblings(e);
        String nodeType = getParentNodeType(e);

        String query = null;
        
        if (isBoolean(nodeType, propertyName)) {
            HashMap<String, String[]> parameters = new HashMap<String, String[]>();
            parameters.put(Constants.PAR_PROPERTY_TYPE, new String[]{""+PropertyType.BOOLEAN});
            parameters.put(Constants.PAR_CONTENT_TYPE, new String[]{Constants.CONTENT_TYPE_ICON});
   
            query = AppletUtil.createQuery(parameters, "UTF-8");
            query = query + "&" + Constants.PAR_PROPERTY_VALUE + "={../@" + propertyName + "}";
        } else {
            HashMap<String, String[]> parameters = new HashMap<String, String[]>();
            parameters.put(Constants.PAR_NODE_TYPE, new String[]{nodeType});
            parameters.put(Constants.PAR_PROPERTY_NAME, new String[]{propertyName});
            parameters.put(Constants.PAR_CONTENT_TYPE, new String[]{Constants.CONTENT_TYPE_ICON});

            query = AppletUtil.createQuery(parameters, "UTF-8");
            query = query + "&" + Constants.PAR_PROPERTY_VALUE + "={../@" + propertyName + "}";
        }

        String image = "<" + Tag.IMG.toString()
                + " "
                + Attribute.SRC.toString()
                + "=\"" + HyperlinkModel.REPOSITORY_URL
                + query
                + "\" "
                + Attribute.TITLE.toString()
                + "=\""
                + "{../@" + propertyName + "}"
                + "\"/>";

        String html = substituteRange(e, image, range.getStartOffset(), range.getEndOffset());

        setOuterHTML(e, html);
    }

    protected boolean isBoolean(String nodeTypeName, String propertyName) {
        NodeTypes nodeTypes = (NodeTypes) getEditor().getProperties().get(Editor.PROP_NODE_TYPES);
        SimpleNamespaceRegistry namespaces = SimpleNamespaceRegistry.getInstance();


        NodeTypeDefinition nodeTypeDefinition = nodeTypes.get(QName.valueOf(namespaces.toQNameString(nodeTypeName)));
        PropertyDefinition[] propertyDefinitions = nodeTypeDefinition.getDeclaredPropertyDefinitions();
        for (PropertyDefinition propertyDefinition : propertyDefinitions) {
            if (namespaces.toPrefixName(propertyDefinition.getName()).equals(propertyName)) {
                if (propertyDefinition.getRequiredType() == PropertyType.BOOLEAN)
                    return true;
                return false;
            }
        }

        return false;
    }
}
